package handler

import (
	"encoding/json"
	"pet-manag/cache"
	"pet-manag/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	pet_name := c.PostForm("petName")
	price := c.PostForm("price")
	if pet_name == "" || price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Pet{
		PetName: pet_name,
		Price:   price,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var pet []models.Pet
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&pet).Order(pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}

	var total int64
	models.DB.Model(models.Pet{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  pet,
		"total": total,
	})
	return
}
